package von.seiji.cn;

import cn.hutool.core.lang.TypeReference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: SeiJi
 * @DateTime: 2022/2/22 15:14
 * @Description: 此人很懒，未写描述！
 **/
public class LayerUtil {

    private String idName;

    private String pidName;

    private String childrenName;

    private LayerUtil(String idName, String pidName, String childrenName) {
        this.idName = idName;
        this.pidName = pidName;
        this.childrenName = childrenName;
    }


    /**
     * 树状 --> 扁平 （只需要childrenName）
     * @param maps
     * @return
     */
    public List<JSONObject> toFlat(List<JSONObject> maps) {
        List<JSONObject> children = maps.stream().flatMap(item -> {
            List<JSONObject> mapList = JSON.parseObject(item.getString(childrenName), new TypeReference<List<JSONObject>>() {
            });
            item.put(childrenName, new ArrayList<JSONObject>());
            return mapList.stream();
        }).collect(Collectors.toList());
        if (!children.isEmpty()) {
            maps.addAll(toFlat(children));
        }
        return maps;
    }


    /**
     * 扁平 --> 树状 （三个字段值都需要指定）
     * @param maps
     * @return
     */
    public List<JSONObject> toTree(List<JSONObject> maps, String topId) {

        List<JSONObject> parents = maps.stream().filter(item -> topId.equals(item.getString(pidName)))
                .map(item -> {
                    item.put(childrenName, toTree(maps, item.getString(idName)));
                    return item;
                }).collect(Collectors.toList());
        return parents;
    }

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder {

        private String idName;

        private String pidName;

        private String childrenName;

        public Builder id(String idName) {
            this.idName = idName;
            return this;
        }

        public Builder pid(String pidName) {
            this.pidName = pidName;
            return this;
        }

        public Builder children(String childrenName) {
            this.childrenName = childrenName;
            return this;
        }

        public LayerUtil build() {
            return new LayerUtil(idName, pidName, childrenName);
        }
    }


}
